import { v4 as uuidv4 } from "uuid";
import { FormType } from "@/types/enum";
import { FileType } from "@/types";

export function isInput(type: FormType) {
  return type === FormType.Input;
}
export function isTextarea(type: FormType) {
  return type === FormType.Textarea;
}

export function isPassword(type: FormType) {
  return type === FormType.Password;
}

export function isInputNumber(type: FormType) {
  return type === FormType.InputNumber;
}
export function isInputGroup(type: FormType) {
  return type === FormType.InputGroup;
}

// 随机生成一个字段名
export function generateField(length = 10): string {
  // 生成一个随机数并转换为36进制字符串
  const random = Math.random()
    .toString(36)
    .substring(2, length - 2);
  // 生成一个随机字母作为开头
  const firstLetter = String.fromCharCode(97 + Math.floor(Math.random() * 26));
  // 生成一个随机字母作为结尾
  const lastLetter = String.fromCharCode(97 + Math.floor(Math.random() * 26));
  return firstLetter + random + lastLetter;
}

/**
 * @description 生成id
 * @returns
 */
export function generateId() {
  return uuidv4();
}

/**
 * @description 深拷贝函数
 * @param obj
 * @returns
 */
export function deepClone<T>(obj: T): T {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map((item) => deepClone(item)) as unknown as T;
  }
  const clonedObj = {} as T;
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      clonedObj[key] = deepClone(obj[key]);
    }
  }
  return clonedObj;
}

export function getBase64(file: FileType): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });
}
